#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

void testMmap(int size) {
  printf("pid:%d\n", getpid());
  int aligned_padded_size = size;
  printf("mmap1: Memory not in use\n");
  void *addr1 = mmap(0, aligned_padded_size, PROT_NONE,
                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  if (addr1 == MAP_FAILED) {
    printf("mmap failed: %s\n", strerror(errno));
    return;
  }
//  sleep(1);

  printf("mmap2: not released after use\n");
  void *addr2 = mmap(0, aligned_padded_size, PROT_READ | PROT_WRITE,
                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  if (addr2 == MAP_FAILED) {
    printf("mmap failed: %s\n", strerror(errno));
    return;
  }
//  sleep(1);

  char *ptr2 = (char *)addr2;
  for (size_t i = 0; i < aligned_padded_size; i++) {
    ptr2[i] = 0;
  }
//  sleep(1);

  printf("mmap3: released after use\n");
  void *addr3 = mmap(0, aligned_padded_size, PROT_READ | PROT_WRITE,
                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  if (addr3 == MAP_FAILED) {
    printf("mmap failed: %s\n", strerror(errno));
    return;
  }
//  sleep(1);

  char *ptr3 = (char *)addr3;
  for (size_t i = 0; i < aligned_padded_size; i++) {
    ptr3[i] = 0;
  }
//  sleep(1);

  munmap(addr3, aligned_padded_size);
//  sleep(1);
}

int main(int argc, char *argv[]) {
  int size = 1024*1024;
  if (argc == 2) {
    // 提取等号后面的数字部分
    std::string arg = argv[1];
    std::string valueStr = arg.substr(7);  // 跳过 "--size="
    size = std::stoi(valueStr);
  }
  printf("use: %d mem_size\n", size);
  testMmap(size);

  return 0;
}
